import { layoutPermission, layoutNoPermission } from '@/router/routes'

/**
 * 使用meta.roleId确定当前用户是否具有权限
 * @param rules 用户拥有的权限规则列表 eg: [1,2,3]
 * @param route 需要过滤的路由
 */
function hasPermission(rules, route) {
  if (route.meta && route.meta.ruleId) {
    // 父路由设置ruleId
    if (rules.includes(route.meta.ruleId)) {
      return true
    } 
    // 如果存在子路由 子路由有一个有权限就返回true 否则false
    if (route.children) {
      const tmp = route.children
      let flag = false
      for (const v of tmp) {
        flag = hasPermission(rules, v)
        if (flag) {
          break
        }
      }
      return flag
    } 
    return false
      
    
  } 
  // 父路由未设置ruleId
  // 如果存在子路由 子路由有一个有权限就返回true 否则false
  if (route.children) {
    const tmp = route.children
    let flag = false
    for (const v of tmp) {
      flag = hasPermission(rules, v)
      if (flag) {
        break
      }
    }
    return flag
  } 
  return true
    
  
}

/**
 * 通过递归过滤需权限校验的路由
 * @param routes layoutPermission
 * @param rules 权限id集合
 */
export function filterLayoutPermission(routes, rules) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(rules, tmp)) {
      if (tmp.children) {
        tmp.children = filterLayoutPermission(tmp.children, rules)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  set_routes: (state, routes) => {
    state.addRoutes = routes
    state.routes = layoutNoPermission.concat(routes)
  }
}

const actions = {
  // 生成新的权限过滤后的路由
  generateRoutes({ commit }, rules) {
    return new Promise(resolve => {
      const accessedRoutes = filterLayoutPermission(layoutPermission, rules)
      commit('set_routes', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
